﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using AutoMapper;
using Microsoft.WindowsAzure.StorageClient;
using AzureGames.Data.Implementation.ServiceEntities;

namespace AzureGames.Data.Implementation
{
    public class UserRepository : AzureTableRepository<UserEntity>, IUserRepository
    {
        const string PartionKey = "User";
        public UserRepository() : base("User") 
        {
            AutoMapper.Mapper.CreateMap<Model.User, ServiceEntities.UserEntity>()
              .ForMember(m => m.PartitionKey, s => s.UseValue("User"))
              .ForMember(m => m.RowKey, s => s.MapFrom(g => g.ID));
            AutoMapper.Mapper.CreateMap<ServiceEntities.UserEntity, Model.User>();
                //ForMember(m => m.Name, s => s.MapFrom(g => g.Name));
        }

        #region IUserRepository impl
        public Model.User LoginUser(string nameIdentifier)
        {            
            return dataContext.CreateQuery<UserEntity>(this.tableName)
                   .Where(n => n.PartitionKey == PartionKey && n.NameIdentifier == nameIdentifier)
                   .FirstOrDefault();
        }

        public Model.User GetUser(string userID)
        {
           
            return Get("User", userID.ToString());
        }


        public void AddUser(Model.User user)
        {
            Add(user);
        }


        public void UpdateUser(Model.User user)
        {
            //SetupAzureTableRepository();
            var storedUser = Get("User", user.ID.ToString());
            if (storedUser != null)
            {
                storedUser.AvatarImage = user.AvatarImage;
                storedUser.Email = user.Email;
                storedUser.FirstName = user.FirstName;
                storedUser.LastName = user.LastName;
                storedUser.Name = user.Name;
            }

            Update(storedUser);
        }

        #endregion

        public List<Model.User> GetUsers()
        {
            return Get("User").Cast<Model.User>().ToList();
        }
    }
}
